package com.ctshk.rpc.payment.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.payment.utils
 * @Author: hef
 * @CreateTime: 2021-04-27 17:24
 * @Description: 支付公共工具
 */
public class PayUtil {


    /**
     * 获取订单号
     *
     * @param paramMap
     * @return
     */
    public static String getOrderNumber(Map<String, String> paramMap) {
        String orderNumber = null;
        //支付宝
        if (paramMap.containsKey("out_trade_no")) {
            orderNumber = paramMap.get("out_trade_no");
        }
        //微信
        else if (paramMap.containsKey("o_sn")) {
            orderNumber = paramMap.get("o_sn");
        }
        //银联
        else if (paramMap.containsKey("orderId")) {
            orderNumber = paramMap.get("orderId");
        }
        //信用卡
        else if (paramMap.containsKey("order")) {
            String order = paramMap.get("order");
            JSONObject jsonObject = JSON.parseObject(order);
            orderNumber = jsonObject.getString("id");
        }
        return orderNumber;
    }

    /**
     * 获取退款单号
     *
     * @param paramMap
     * @return
     */
    public static String getRefundNumber(Map<String, String> paramMap) {
        String orderNumber = null;
        if (paramMap.containsKey("orderId")) {
            orderNumber = paramMap.get("orderId");
        }
        return orderNumber;
    }

    /**
     * 删除不必要的参数
     *
     * @param parameters
     */
    public static void removeUnnecessaryParams(Map<String, String> parameters) {
        List<String> unnecessaryParams = parameters.entrySet().stream()
                .filter(a1 -> a1.getValue() == null || a1.getValue().length() == 0 || a1.getValue().equals("null"))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        unnecessaryParams.forEach(parameters::remove);
    }

    /**
     * url,doGet
     *
     * @param gateway
     * @param charset
     * @param parameters
     * @return
     */
    public static String generateGetUrl(String gateway, String charset, Map<String, String> parameters) {
        String query = parameters.entrySet().stream().map(a1 -> {
            try {
                return a1.getKey() + "=" + URLEncoder.encode(a1.getValue(), charset);
            } catch (UnsupportedEncodingException e) {
                return a1.getKey() + "=" + a1.getValue();
            }
        }).collect(Collectors.joining("&"));
        return gateway + "?" + query;
    }

    /**
     * 功能：构造用于前台交易的HTTP POST并自动提交表单。<br>
     *
     * @param reqUrl   :   address for submitting forms<br>
     * @param hiddens  :  Form key values stored in form of MAP<br>
     * @param encoding : Send the value of the field encoding in the request message domain<br>
     * @return Transaction forms for constructed HTTP POST<br>
     */
    public static String createAutoFormHtml(String reqUrl, Map<String, String> hiddens, String encoding) {
        StringBuffer sf = new StringBuffer();
        sf.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + encoding + "\"/></head><body>");
        sf.append("<form id = \"pay_form\" action=\"" + reqUrl
                + "\" method=\"post\">");
        if (null != hiddens && 0 != hiddens.size()) {
            Set<Map.Entry<String, String>> set = hiddens.entrySet();
            Iterator<Map.Entry<String, String>> it = set.iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> ey = it.next();
                String key = ey.getKey();
                String value = ey.getValue();
                sf.append("<input type=\"hidden\" name=\"" + key + "\" id=\""
                        + key + "\" value=\"" + value + "\"/>");
            }
        }
        sf.append("</form>");
        sf.append("</body>");
        sf.append("<script type=\"text/javascript\">");
        sf.append("document.all.pay_form.submit();");
        sf.append("</script>");
        sf.append("</html>");
        return sf.toString();
    }

    /**
     * 功能：构造用于前台交易的HTTP POST并自动提交表单。<br>
     *
     * @param reqUrl:   address for submitting forms<br>
     * @param hiddens:  Form key values stored in form of MAP<br>
     * @param encoding: Send the value of the field encoding in the request message domain<br>
     * @return Transaction forms for constructed HTTP POST<br>
     */
    public static String createAutoForm(String reqUrl, Map<String, String> hiddens) {
        StringBuffer sf = new StringBuffer();
        sf.append("<form id = \"pay_form\" action=\"" + reqUrl
                + "\" method=\"post\">");
        if (null != hiddens && 0 != hiddens.size()) {
            Set<Map.Entry<String, String>> set = hiddens.entrySet();
            Iterator<Map.Entry<String, String>> it = set.iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> ey = it.next();
                String key = ey.getKey();
                String value = ey.getValue();
                sf.append("<input type=\"hidden\" name=\"" + key + "\" id=\""
                        + key + "\" value=\"" + value + "\"/>");
            }
            sf.append("<button id=\"submit-btn\" type=\"submit\" class=\"\">立即支付</button>");
        }
        sf.append("</form>");
        return sf.toString();
    }


    /**
     * 组成App需要的OrderInfo
     *
     * @param parameters
     * @return
     */
    public static String joinParams(Map<String, String> parameters) {
        return parameters.entrySet().stream().
                sorted(Comparator.comparing(Map.Entry::getKey)).
                map(a1 -> a1.getKey() + "=\"" + a1.getValue() + "\"").collect(Collectors.joining("&"));
    }
}
